<script setup>
import { ref, computed } from 'vue'
import { usePlayerStore, usePlaylistStore } from '@/store'
import { ElCard, ElButton, ElIcon, ElTooltip, ElEmpty, ElDrawer } from 'element-plus'
import { Delete, Sort, Check, Close, VideoPlay, VideoPause } from '@element-plus/icons-vue'

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

const playerStore = usePlayerStore()
const playlistStore = usePlaylistStore()

// 状态变量
const isSortable = ref(false)
const hoveredSongId = ref(null)
const dragStartIndex = ref(null) // 拖拽开始时的索引

// 播放列表中的歌曲
const playlistSongs = computed(() => {
  return playlistStore.playlist
})

// 当前播放索引
const currentIndex = computed(() => {
  return playlistStore.currentSongIndex
})

// 从播放列表中移除歌曲
const removeFromPlaylist = (songId) => {
  playlistStore.removeFromPlaylist(songId)
}

// 从播放列表中播放歌曲
const playFromPlaylist = (song, index) => {
  // 如果处于排序模式，点击不应该播放
  if (isSortable.value) return
  
  playlistStore.playFromPlaylist(song)
}

// 清空播放列表
const clearPlaylist = () => {
  playlistStore.clearPlaylist()
}

// 开始拖拽排序
const startSorting = () => {
  isSortable.value = true
}

// 结束拖拽排序
const stopSorting = () => {
  isSortable.value = false
}

// 关闭播放列表
const closePlaylist = () => {
  emit('close')
}

// 判断歌曲是否正在播放
const isCurrentSong = (songId) => {
  return playerStore.currentSong.id === songId
}

// 判断当前歌曲是否正在播放
const isCurrentPlaying = (songId) => {
  return isCurrentSong(songId) && playerStore.isPlaying
}

// 播放/暂停切换
const togglePlayStatus = (song, index, event) => {
  // 如果处于排序模式，点击不应该播放
  if (isSortable.value) return
  
  // 阻止事件冒泡，避免触发卡片的点击事件
  event.stopPropagation()
  
  if (isCurrentSong(song.id)) {
    // 如果是当前歌曲，切换播放状态
    playerStore.togglePlay()
  } else {
    // 播放新的歌曲
    playlistStore.playFromPlaylist(song)
  }
}

// 设置悬浮歌曲
const setHovered = (songId) => {
  hoveredSongId.value = songId
}

// 清除悬浮状态
const clearHovered = () => {
  hoveredSongId.value = null
}

// 判断是否悬浮
const isHovered = (songId) => {
  return hoveredSongId.value === songId
}

// 拖拽开始
const handleDragStart = (event, index) => {
  // 只有在排序模式下才允许拖拽
  if (!isSortable.value) {
    event.preventDefault()
    return
  }
  
  // 设置拖拽效果
  event.dataTransfer.effectAllowed = 'move'
  
  // 记录起始位置
  dragStartIndex.value = index
  
  // 添加拖拽中的类
  event.target.classList.add('dragging')
}

// 拖拽悬停
const handleDragOver = (event) => {
  // 阻止默认行为以允许放置
  event.preventDefault()
  
  // 设置拖拽效果
  event.dataTransfer.dropEffect = 'move'
}

// 拖拽放置
const handleDrop = (event, endIndex) => {
  // 阻止默认行为
  event.preventDefault()
  
  // 确保有有效的起始索引
  if (dragStartIndex.value === null) return
  
  // 确保不是放在同一位置
  if (dragStartIndex.value === endIndex) return
  
  // 使用 playlistStore 的方法执行排序
  playlistStore.reorderPlaylist(dragStartIndex.value, endIndex)
  
  // 重置起始索引
  dragStartIndex.value = null
}

// 拖拽结束
const handleDragEnd = (event) => {
  // 移除拖拽中的类
  event.target.classList.remove('dragging')
  
  // 重置起始索引
  dragStartIndex.value = null
}
</script>

<template>
  <el-drawer
    v-model="props.isVisible"
    title="播放列表"
    :show-close="false"
    direction="rtl"
    :with-header="false"
    :size="350"
    :modal-class="'playlist-drawer-modal'"
    @close="closePlaylist"
    style="background-color: #2e2e2e;"
  >
    <div class="playlist-container">
      <div class="playlist-header">
        <div class="playlist-title">
          <span>播放列表 ({{ playlistSongs.length }})</span>
        </div>
        <div class="playlist-actions">
          <el-button type="text" @click="startSorting" v-if="!isSortable">
            <el-icon><Sort /></el-icon>
            <span>排序</span>
          </el-button>

          <el-button type="text" @click="stopSorting" v-else>
            <el-icon><Check /></el-icon>
            <span>完成</span>
          </el-button>

          <el-button type="text" @click="clearPlaylist">
            <el-icon><Delete /></el-icon>
            <span>清空</span>
          </el-button>
          
          <el-button type="text" @click="closePlaylist" class="close-btn">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      
      <div class="playlist-content">
        <el-empty v-if="playlistSongs.length === 0" 
          description="播放列表还是空的" 
          :image-size="100">
          <span class="empty-tip">快去首页添加喜欢的歌曲吧</span>
        </el-empty>
        
        <div v-else class="playlist-songs">
          <div 
            v-for="(song, index) in playlistSongs" 
            :key="song.id"
            :class="{ 
              'playlist-item': true, 
              'dragging': isSortable && dragStartIndex === index,
              'sortable': isSortable
            }"
            draggable="true"
            @dragstart="handleDragStart($event, index)"
            @dragover="handleDragOver($event)"
            @drop="handleDrop($event, index)"
            @dragend="handleDragEnd($event)"
            @mouseenter="setHovered(song.id)"
            @mouseleave="clearHovered"
          >
            <el-card 
              shadow="always" 
              :class="{ 'current-song-card': isCurrentSong(song.id) }"
              @click="playFromPlaylist(song, index)"
              style="background-color: #181818;"
            >
              <div class="card-content">
                <div class="song-left">
                  <div 
                    class="play-icon-wrapper"
                    @click.stop="togglePlayStatus(song, index, $event)"
                  >
                    <!-- 当前正在播放状态 -->
                    <el-icon v-if="isCurrentPlaying(song.id)" class="playing-icon">
                      <VideoPause />
                    </el-icon>
                    
                    <!-- 当前选中但暂停状态 -->
                    <el-icon v-else-if="isCurrentSong(song.id)" class="playing-icon">
                      <VideoPlay />
                    </el-icon>
                    
                    <!-- 悬浮状态显示播放图标 -->
                    <el-icon v-else-if="isHovered(song.id) && !isSortable" class="hover-icon">
                      <VideoPlay />
                    </el-icon>
                    
                    <!-- 默认显示序号 -->
                    <div v-else class="song-index">{{ index + 1 }}</div>
                  </div>
                </div>
                
                <div class="song-info">
                  <div class="song-title">{{ song.title }}</div>
                  <div class="song-artist">{{ song.artist }}</div>
                </div>
                
                <div class="song-actions">
                  <el-button type="text" size="small" @click.stop="removeFromPlaylist(song.id)" class="remove-btn">
                    <el-icon><Close /></el-icon>
                  </el-button>
                  
                  <div v-if="isSortable" class="drag-handle">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <line x1="8" y1="6" x2="16" y2="6"></line>
                      <line x1="8" y1="12" x2="16" y2="12"></line>
                      <line x1="8" y1="18" x2="16" y2="18"></line>
                    </svg>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped>
/* 自定义 ElDrawer 样式 */
:deep(.el-drawer) {
  background-color: #1e1e1e;
  color: #fff;
}

:deep(.el-drawer__body) {
  padding: 0;
  overflow: hidden;
}

/* 播放列表容器 */
.playlist-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  color: #fff;
}

/* 播放列表头部 */
.playlist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #333;
}

.playlist-title {
  font-size: 18px;
  font-weight: 500;
}

.playlist-actions {
  display: flex;
  align-items: center;
}

.el-button {
  color: #ccc;
}

.el-button:hover {
  color: #fff;
}

.close-btn {
  margin-left: 15px;
}

/* 播放列表内容 */
.playlist-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

/* 滚动条样式 */
.playlist-content::-webkit-scrollbar {
  width: 6px;
}

.playlist-content::-webkit-scrollbar-track {
  background: #333;
}

.playlist-content::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 3px;
}

.playlist-content::-webkit-scrollbar-thumb:hover {
  background: #777;
}

/* 空播放列表 */
.empty-tip {
  font-size: 14px;
  opacity: 0.7;
}

/* 播放列表歌曲 */
.playlist-songs {
  list-style: none;
  padding: 10px;
  margin: 0;
}

.playlist-item {
  margin-bottom: 10px;
  transition: transform 0.2s;
  position: relative;
}

.playlist-item:last-child {
  margin-bottom: 0;
}

/* 卡片样式 */
:deep(.el-card) {
  background-color: #2a2a2a;
  border: none;
  border-radius: 8px;
  color: #fff;
  margin-bottom: 8px;
  transition: all 0.3s;
}

:deep(.el-card.current-song-card) {
  background-color: rgba(255, 59, 59, 0.2);
}

:deep(.el-card__body) {
  padding: 12px;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.card-content {
  display: flex;
  align-items: center;
}

.song-left {
  width: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.play-icon-wrapper {
  cursor: pointer;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.song-index {
  font-size: 14px;
  color: #999;
}

.playing-icon {
  color: #FF3B3B;
  font-size: 18px;
}

.hover-icon {
  color: #fff;
  font-size: 18px;
  opacity: 0.8;
}

/* 悬浮时显示更清晰的图标 */
.play-icon-wrapper:hover .hover-icon {
  opacity: 1;
  transform: scale(1.1);
}

/* 添加过渡效果 */
.play-icon-wrapper .el-icon {
  transition: all 0.2s;
}

.song-info {
  flex: 1;
  min-width: 0;
  padding: 0 15px;
}

.song-title {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 4px;
}

.current-song-card .song-title {
  color: #FF3B3B;
  font-weight: 500;
}

.song-artist {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-actions {
  display: flex;
  align-items: center;
}

.remove-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.el-card:hover .remove-btn {
  opacity: 1;
}

.remove-btn:hover {
  color: #FF3B3B;
}

.drag-handle {
  cursor: grab;
  color: #999;
  margin-left: 10px;
}

.dragging {
  cursor: grabbing;
}

/* 自定义遮罩层样式，使其半透明 */
:deep(.playlist-drawer-modal) {
  background-color: rgba(0, 0, 0, 0.5);
}

/* 响应式调整 */
@media screen and (max-width: 576px) {
  :deep(.el-drawer) {
    width: 100% !important;
  }
}

/* 添加拖拽相关的样式 */
.sortable {
  cursor: grab !important;
}

.sortable:active {
  cursor: grabbing !important;
}

.dragging {
  opacity: 0.6;
  z-index: 10;
}

/* 显示拖拽把手时的样式调整 */
.drag-handle {
  cursor: grab;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
}

.drag-handle:active {
  cursor: grabbing;
}

/* 排序模式下卡片样式修改 */
:deep(.sortable .el-card) {
  transition: transform 0.1s, box-shadow 0.2s;
}

:deep(.sortable .el-card:hover) {
  transform: translateX(5px);
  box-shadow: -3px 0 5px rgba(255, 59, 59, 0.2);
}

/* 在排序模式下禁用点击效果 */
.sortable .play-icon-wrapper {
  cursor: grab !important;
}

.sortable .card-content {
  pointer-events: none;
}

.sortable .song-actions {
  pointer-events: auto; /* 允许动作区域响应事件 */
}

.sortable .drag-handle {
  pointer-events: auto;
}

.sortable .remove-btn {
  pointer-events: auto;
}
</style> 